package cn.detu.coolshark.controller;

import cn.detu.coolshark.entity.Product;
import cn.detu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class ProductController {
    @Value("${dirPath}")
    private String dirPath;

    @Autowired(required = false)
    ProductMapper mapper;

    @RequestMapping("/upload/product")
    public String upload(MultipartFile picFile) throws IOException {
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        String filePath = dirPath + "/" + fileName;
        picFile.transferTo(new File(filePath));
        return fileName;
    }

    @RequestMapping("/product/select")
    public List<Product> select() {
        return mapper.select();
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectB() {
        return mapper.selectB();
    }

    @RequestMapping("/product/select/top")
    public List<Product> selectC() {
        return mapper.selectC();
    }

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product) {
        product.setCreated(new Date());
        mapper.insert(product);
    }


    @RequestMapping("/product/delete")
    public void delete(int id) {
        String url = mapper.selectUrlById(id);
        String filePath = dirPath + "/" + url;
        new File(filePath).delete();
        mapper.delete(id);

    }


    @RequestMapping("/product/select/category")
    public List<Product> selectD(int cid) {
        return mapper.selectD(cid);
    }

    @RequestMapping("/search")
    public List<Product> selectE(String wd){
        return mapper.selectE(wd);

    }

    @RequestMapping("/product/test")
    public List<Product> selectF(){
        return mapper.selectF();
    }

    @RequestMapping("/product/selectById")
    public Product selectById(int id){
        mapper.updateByViewCount(id);
        return mapper.selectById(id);
    }

}
